package it.tempogara.tgsender;

import it.tempogara.tgsender.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.StringTokenizer;

import org.apache.commons.net.ftp.FTPClient;

import android.R.array;
import android.app.Activity;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

public class MyThreadSender extends AsyncTask<Void, Integer, Void>{
	
	Activity a;
	boolean download;
	boolean send;
	String readerAddr;
	String content;
	String type;
	String sendAddressEmail;	
	String sendAddressFtp;
	String seconds;
	ArrayList<String> log;
	ArrayList<String> files;
	String user;
	String passw;
	String tagsFile;
	File fTemp;
	TextView logText;
	public boolean last;
	public boolean multiple;
	String fileLog = "log.txt";
	FileOutputStream fosLog;
	BufferedWriter writerLog;
	ToneGenerator tg;
	int count;
	boolean stop;
	ScrollView scroll;
	boolean clean;
	boolean running;
//	booelan multiple;
	WifiManager wifiManager;
	ApplicationData appData;
	
	public MyThreadSender(Activity a){
		this.a = a;
		last = true;
		multiple = false;
		stop = false;
		clean=false;
		log = new ArrayList<String>();
		tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 400);
		appData = (ApplicationData) a.getApplication();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(a);
		sendAddressEmail = prefs.getString("AddressEmail", "info@tempogara.it");
		sendAddressFtp = prefs.getString("Address", "www.tempogara.it");
		user = prefs.getString("User", "1843848@aruba.it");
		passw = prefs.getString("Passw", "bgqa4uos");
		readerAddr = appData.ipReader;
	}
	
	protected void onPreExecute(){
		logText = (TextView) a.findViewById(R.id.textViewLog);
		logText.setText("");
		scroll=(ScrollView) a.findViewById(R.id.ScrollLog);
	}
	
	protected void onPostExecute(){
		this.cancel(true);
		
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		try {
			if(download)
				sendLast();
			else if(send)
				inviaCartella();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		return null;
	}
	
	protected void onProgressUpdate(Integer... progress) {
		if(clean){
			logText.setText("");
			clean=false;
		}
		for(int i =0;i<log.size();i++)
			logText.append(log.get(i));
	}
	
	private String download(String address) {
		String output;
		OutputStream out;
		InputStream in;
		output = null;
		out = null;
		in = null;
		
		try {
			URL url = new URL(address);
			out = new ByteArrayOutputStream();
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(2000);
			conn.setReadTimeout(2000);
			in = conn.getInputStream();
			byte buffer[] = new byte[1024];
			int numRead;
			while ((numRead = in.read(buffer)) != -1)
				out.write(buffer, 0, numRead);
			output = out.toString();
			System.out.println((new StringBuilder("Scaricato:")).append(output).toString());
		} catch (Exception exception) {
		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
			} catch (IOException ioexception) {
			}
		}
		return output;
	}
	
	public void sendLast() throws Exception{
		HashMap<String, Object> mapRes = new HashMap<String, Object>();
		int lastDownloadSize = 0;
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(a);
		type = prefs.getString("Type","UPLOAD");
//		readerAddr = prefs.getString("IP", "192.168.10.20");
		sendAddressFtp = prefs.getString("Address", "www.tempogara.it");
		sendAddressEmail = prefs.getString("AddressEmail", "info@tempogara.it");
		user = prefs.getString("User", "1843848@aruba.it");
		passw = prefs.getString("Passw", "bgqa4uos");
		if(!readerAddr.startsWith("http://"))
			readerAddr = "http://"+readerAddr;
		mapRes.put("lastDownloadSize", lastDownloadSize);
		if (!readerAddr.endsWith("/"))
			readerAddr += "/";
		log.add("Scarico il summary dal reader \n");
		count++;
		publishProgress(count);
		log.clear();
		if(multiple)
			appData.tagsFile= new String[Integer.valueOf(prefs.getString("Number", "5"))];
		else
			appData.tagsFile = new String[1];
		String summary = download((new StringBuilder(String.valueOf(readerAddr))).append("cgi-bin/summary.sh").toString());
		if (summary != null) {
			log.add("Summary scaricato \n");
			log.clear();
			count++;
			publishProgress(count);
			log.clear();
			StringTokenizer st = new StringTokenizer(summary, ",");
			int countTok = st.countTokens();
			if (countTok < 4){
				log.add("Output summary.sh non valido \n");
				count++;
				publishProgress(count);
				log.clear();
			}
			String sysid = st.nextToken();
			String dateTime = st.nextToken();
			mapRes.put("SYSID", sysid);
			mapRes.put("DATAORA", dateTime);
			mapRes.put("VALTIME", st.nextToken());
			tagsFile = st.nextToken();
			appData.tagsFile[0]=tagsFile;
			String mrkFile = st.nextToken();
			if (countTok == 6) {
				String pid = st.nextToken();
				if (pid.trim().length() == 0){
					log.add("ReaderError \n");
					count++;
					publishProgress(count);
					log.clear();
				}
					
			}
			StringTokenizer sttags = new StringTokenizer(tagsFile, "-.");
			if (sttags.countTokens() < 4){
				log.add("Formato Nome file non valido (=file-<nome reader>-<progressivo>.tags \n");
				count++;
				publishProgress(count);
				log.clear();
			}
			sttags.nextToken();
			sttags.nextToken();
			String progr = sttags.nextToken();
			int iprogr = 0;
			try {
				iprogr = Integer.parseInt(progr);
			} catch (NumberFormatException e) {
				log.add("Formato Nome file non valido (=file-<nome reader>-<progressivo>.tags \n");
				count++;
				publishProgress(count);
				log.clear();
			}
			String fileAddr = (new StringBuilder(String.valueOf(readerAddr))).append("files/").append(tagsFile).toString();
			String fileAddrMrk = (new StringBuilder(String.valueOf(readerAddr))).append("files/").append(mrkFile).toString();
			if(multiple)
				log.add("Scarico i file dei rilevamenti \n");
			else
				log.add("Scarico il file dei rilevamenti \n");
			count++;
			publishProgress(count);
			content = download(fileAddr);
			log.clear();
			if(content==null){
				log.add("File non scaricato correttamente o vuoto \n");
				count++;
				publishProgress(count);
				log.clear();
			}
			String DirPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/TGSender/"+new SimpleDateFormat("ddMMyyyy").format(new Date()); 
			if(!new File(DirPath).exists()){
				File fTemp = new File(DirPath);
				fTemp.mkdir();
			}
			File f = new File(DirPath+"/"+appData.tagsFile[0]);//a.getBaseContext().getFileStreamPath(tagsFile);
			
			if(f.exists()){
				if(f.delete())
					f.createNewFile();
			}else
				f.createNewFile();
			FileOutputStream fos = new FileOutputStream(f);//.openFileOutput(tagsFile, a.MODE_APPEND);
			fos.write(content.getBytes());
			BufferedReader bfTemp = new BufferedReader(new FileReader(f));
			int countLines = 0;
			
			while(bfTemp.readLine()!=null){
				countLines++;
			}
			
			log.add("File scaricato correttamente in "+DirPath+"/"+tagsFile+"\n");
			log.add("Letti "+countLines+" rilevamenti \n");
			if(appData.counterRilevamenti!=0 && countLines>appData.counterRilevamenti){
				log.add("Nuovi rilevamenti: "+(countLines-appData.counterRilevamenti)+"\n");
			}
			appData.counterRilevamenti=countLines;
			count++;
			publishProgress(count);
			log.clear();
			StringTokenizer sttags2 = new StringTokenizer(tagsFile, "-.");
			if (sttags2.countTokens() < 4){
				log.add("Formato Nome file non valido (=file-<nome reader>-<progressivo>.tags \n");
				count++;
				publishProgress(count);
				log.clear();
				count++;
				publishProgress(count);
			}else{
				String tagsFileIn = sttags2.nextToken()+"-"+sttags2.nextToken()+"-";
				
				int indexProgr = Integer.parseInt(sttags2.nextToken());
	
				for(int i =1;i<appData.tagsFile.length;i++){
					String tagsFileNew = tagsFileIn + (indexProgr-i)+".tags";
					String fileAddrNew = (new StringBuilder(String.valueOf(readerAddr))).append("files/").append(tagsFileNew).toString();
					log.add("Scarico il file dei rilevamenti #"+i+" \n");
					content = download(fileAddrNew);
					log.clear();
					count++;
					publishProgress(count);
					if(content==null){
						log.add("File non scaricato correttamente o vuoto \n");
						count++;
						publishProgress(count);
						log.clear();
					}
					File fNew = new File(DirPath+"/"+tagsFileNew);//a.getBaseContext().getFileStreamPath(tagsFileNew);
					if(fNew.exists()){
						if(fNew.delete())
							fNew.createNewFile();
					}else
						fNew.createNewFile();
					FileOutputStream fosNew = new FileOutputStream(fNew);//.openFileOutput(tagsFileNew, a.MODE_APPEND);
					fosNew.write(content.getBytes());
					bfTemp = new BufferedReader(new FileReader(fNew));
					countLines = 0;
					while(bfTemp.readLine()!=null){
						countLines++;
					}
					log.add("File scaricato correttamente in "+DirPath+"/"+tagsFileNew+"\n");
					log.add("Letti "+countLines+" rilevamenti \n");
					
					if(appData.counterRilevamenti!=0 && countLines>appData.counterRilevamenti){
						log.add("Nuovi rilevamenti: "+(countLines-appData.counterRilevamenti)+"\n");
					}
					appData.counterRilevamenti=countLines;
					count++;
					publishProgress(count);
					log.clear();
					appData.tagsFile[i]=tagsFileNew;
				}
				bfTemp.close();
				fos.close();
				log.add(" *** DOWNLOAD TERMINATO *** \n");
				count++;
				publishProgress(count);
				log.clear();
				
			}

		}else{
			log.add("Connessione non riuscita \n");
			count++;
			publishProgress(count);
			log.clear();
		}
	
	}
	
	
	private void inviaCartella(){
		String DirPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/TGSender/"+new SimpleDateFormat("ddMMyyyy").format(new Date()); 
		File fOd = new File(DirPath);
		String[] arrayFiles = null;
		if(fOd.exists()){
			arrayFiles=fOd.list();
		}
		if(arrayFiles==null || arrayFiles.length==0){
			log.add("Cartella vuota o non ancora creata, effettua almeno un download");
			count++;
			publishProgress(count);
			log.clear();
		}else{
			Mail m = new Mail("tgsendertempogara@gmail.com", "jordan72");
			m.set_to(new String[]{sendAddressEmail});
			m.set_from("info@tempogara.it");
			m.set_subject("invio rilevamenti "+new SimpleDateFormat("ddMMyyyy").format(new Date()));
			m.setBody("Rilevamenti del giorno inviati tramite l'app Android TGSender");

			for(int i =0;i<arrayFiles.length;i++){
				File f = new File(DirPath+"/"+arrayFiles[i]);//files.get(i));
				if(f.exists()){

					try {
						m.addAttachment(f.getAbsolutePath());
						
					}catch (IOException e) {
						e.printStackTrace();
						log.add("Email non inviata \n"+e.toString());
						count++;
						publishProgress(count);
						log.clear();
					} catch (Exception e) {
						e.printStackTrace();
						log.add("Email non inviata \n"+e.toString());
						count++;
						publishProgress(count);
						log.clear();
					}
					

				 }else{
					 log.add("Allegato non trovato \n");
					 count++;
					 publishProgress(count);
					 log.clear();
				 }
			}
			
			try {
				if(m.send()){
					log.add("Invio email eseguito - "+new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(new Date())+" \n");
					count++;
					publishProgress(count);
					log.clear();
				    tg.startTone(ToneGenerator.TONE_PROP_BEEP);
				}else{
					log.add("Invio email non corretto \n");
					count++;
					publishProgress(count);
					log.clear();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
				log.add("Invio email non corretto \n"+e2.toString());
				count++;
				publishProgress(count);
				log.clear();
			}
					
			//Invio FTP
			FTPClient ftpclient = new FTPClient();
			boolean corretto=false;
			try {
				log.add("Connessione al server FTP \n ");
				count++;
				publishProgress(count);
				log.clear();
				ftpclient.connect(sendAddressFtp);
				log.add("Login in corso \n ");
				count++;
				publishProgress(count);
				log.clear();
				ftpclient.login(user, passw);
				String trial= String.valueOf(ftpclient.getReplyCode());
				if(String.valueOf(ftpclient.getReplyCode()).startsWith("2")){
					if(sendAddressFtp.equals("www.tempogara.it")){
					    ftpclient.changeWorkingDirectory("www.tempogara.it");
					    ftpclient.changeWorkingDirectory("appUpload");
					    if(!ftpclient.changeWorkingDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()))){
					    	ftpclient.makeDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()));
					    	ftpclient.changeWorkingDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()));
					    }
					}
					for(int i = 0; i<arrayFiles.length;i++){
							fTemp= new File(DirPath+"/"+arrayFiles[i]);//files.get(i));
							log.add("Connessione effettuata con successo \n Invio in corso \n");
							count++;
							publishProgress(count);
							log.clear();
							try {
							ftpclient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
					        ftpclient.enterLocalPassiveMode();
					        FileInputStream in = new FileInputStream(fTemp);
					        boolean result = ftpclient.storeFile(fTemp.getName(), in);
					        if(result){
					        	log.add("Upload su FTP effettuato con successo - "+new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(new Date())+" \n");
								count++;
								publishProgress(count);
								log.clear();
								corretto=true;
								log.add(" *** INVIO TERMINATO *** \n");
								count++;
								publishProgress(count);
								log.clear();
							    tg.startTone(ToneGenerator.TONE_PROP_BEEP);
					        }else{
					        	log.add("Upload non effettuato \n");
					        	log.add(ftpclient.getReplyString()+" \n");
								count++;
								publishProgress(count);
								log.clear();
					        }
								in.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
					}
				}else{
					log.clear();
					log.add("Invio dei file non corretto");
					count++;
					publishProgress(count);
				}
			} catch (SocketException e1) {
					// TODO Auto-generated catch block
					log.add("Problemi di connessione al server \n");
					count++;
					publishProgress(count);
					log.clear();
					e1.printStackTrace();
			} catch (IOException e1) {
					log.add("Problemi di connessione al server \n");
					count++;
					publishProgress(count);
					log.clear();
					// TODO Auto-generated catch block
					e1.printStackTrace();
			}
		}
	}
	
	private void invia(){
		log.add("Invio email in corso \n");
		count++;
		publishProgress(count);
		log.clear();
		String DirPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/TGSender/"+new SimpleDateFormat("ddMMyyyy").format(new Date()); 
		Mail m = new Mail("tgsendertempogara@gmail.com", "jordan72");
		m.set_to(new String[]{sendAddressEmail});
		m.set_from("info@tempogara.it");
		m.set_subject("invio rilevamenti");
		m.setBody("Rilevamenti inviati tramite l'app Android TGSender");

		for(int i =0;i<appData.tagsFile.length;i++){
			File f = new File(DirPath+"/"+appData.tagsFile[i]);//files.get(i));
			if(f.exists()){

				try {
					m.addAttachment(f.getAbsolutePath());
					
				}catch (IOException e) {
					e.printStackTrace();
					log.add("Email non inviata \n"+e.toString());
					count++;
					publishProgress(count);
					log.clear();
				} catch (Exception e) {
					e.printStackTrace();
					log.add("Email non inviata \n"+e.toString());
					count++;
					publishProgress(count);
					log.clear();
				}
				

			 }else{
				 log.add("Allegato non trovato \n");
				 count++;
				 publishProgress(count);
				 log.clear();
			 }
		}
		
		try {
			if(m.send()){
				log.add("Invio email eseguito - "+new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(new Date())+" \n");
				count++;
				publishProgress(count);
				log.clear();
			    tg.startTone(ToneGenerator.TONE_PROP_BEEP);
			}else{
				log.add("Invio email non corretto \n");
				count++;
				publishProgress(count);
				log.clear();
			}
		} catch (Exception e2) {
			e2.printStackTrace();
			log.add("Invio email non corretto \n"+e2.toString());
			count++;
			publishProgress(count);
			log.clear();
		}
				
		//Invio FTP
		FTPClient ftpclient = new FTPClient();
		boolean corretto=false;
		try {
			log.add("Connessione al server FTP \n ");
			count++;
			publishProgress(count);
			log.clear();
			ftpclient.connect(sendAddressFtp);
			log.add("Login in corso \n ");
			count++;
			publishProgress(count);
			log.clear();
			ftpclient.login(user, passw);
			String trial= String.valueOf(ftpclient.getReplyCode());
			if(String.valueOf(ftpclient.getReplyCode()).startsWith("2")){
				if(sendAddressFtp.equals("www.tempogara.it")){
				    ftpclient.changeWorkingDirectory("www.tempogara.it");
				    ftpclient.changeWorkingDirectory("appUpload");
				    if(!ftpclient.changeWorkingDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()))){
				    	ftpclient.makeDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()));
				    	ftpclient.changeWorkingDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()));
				    }
				}
				for(int i = 0; i<appData.tagsFile.length;i++){
						fTemp= new File(DirPath+"/"+appData.tagsFile[i]);//files.get(i));
						log.add("Connessione effettuata con successo \n Invio in corso \n");
						count++;
						publishProgress(count);
						log.clear();
						try {
						ftpclient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
				        ftpclient.enterLocalPassiveMode();
				        FileInputStream in = new FileInputStream(fTemp);
				        boolean result = ftpclient.storeFile(fTemp.getName(), in);
				        if(result){
				        	log.add("Upload su FTP effettuato con successo - "+new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(new Date())+" \n");
							count++;
							publishProgress(count);
							log.clear();
							corretto=true;
							log.add(" *** INVIO TERMINATO *** \n");
							count++;
							publishProgress(count);
							log.clear();
						    tg.startTone(ToneGenerator.TONE_PROP_BEEP);
				        }else{
				        	log.add("Upload non effettuato \n");
				        	log.add(ftpclient.getReplyString()+" \n");
							count++;
							publishProgress(count);
							log.clear();
				        }
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
				}
			}else{
				log.clear();
				log.add("Invio dei file non corretto");
				count++;
				publishProgress(count);
			}
		} catch (SocketException e1) {
				// TODO Auto-generated catch block
				log.add("Problemi di connessione al server \n");
				count++;
				publishProgress(count);
				log.clear();
				e1.printStackTrace();
		} catch (IOException e1) {
				log.add("Problemi di connessione al server \n");
				count++;
				publishProgress(count);
				log.clear();
				// TODO Auto-generated catch block
				e1.printStackTrace();
		}
		
	}
	
	private void send() throws FileNotFoundException, IOException{
		String DirPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/TGSender"; 
			log.add("Invio email in corso \n");
			count++;
			publishProgress(count);
			log.clear();
			
			Mail m = new Mail("tgsendertempogara@gmail.com", "jordan72");
			m.set_to(new String[]{sendAddressEmail});
			m.set_from("info@tempogara.it");
			m.set_subject("invio rilevamenti");
			m.setBody("Rilevamenti inviati tramite l'app Android TGSender");
			if(multiple){
				for(int i =0;i<appData.tagsFile.length;i++){
					File f = new File(DirPath+"/"+appData.tagsFile[i]);//files.get(i));
					if(f.exists()){
				try {
					m.addAttachment(f.getAbsolutePath());
				
				} catch (IOException e) {
					e.printStackTrace();
					log.add("Allegato non aggiunto \n");
					count++;
					publishProgress(count);
					log.clear();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					log.add("Allegato non aggiunto \n");
					count++;
					publishProgress(count);
					log.clear();
				}
			 }else{
				 log.add("Allegato non trovato \n");
				 count++;
				 publishProgress(count);
				 log.clear();
			 }
			}
		}else{
				File f = new File(DirPath+"/"+appData.tagsFile[0]);
				if(f.exists()){
					
							try {
								m.addAttachment(f.getAbsolutePath());
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								log.add("Allegato non aggiunto \n");
								count++;
								publishProgress(count);
								log.clear();
							}
					}
		}
			
			try {
				if(m.send()){
					log.add("Invio email eseguito - "+new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(new Date())+" \n");
					count++;
					publishProgress(count);
					log.clear();
				    tg.startTone(ToneGenerator.TONE_PROP_BEEP);
				}else{
					log.add("Invio email non corretto \n");
					count++;
					publishProgress(count);
					log.clear();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			FTPClient ftpclient = new FTPClient();
			boolean corretto=false;
			try {
				
				log.add("Connessione al server FTP \n ");
				count++;
				publishProgress(count);
				log.clear();
				ftpclient.connect(sendAddressFtp);
				log.add("Login in corso \n ");
				count++;
				publishProgress(count);
				log.clear();
				ftpclient.login(user, passw);
				if(sendAddressFtp.equals("www.tempogara.it")){
				    ftpclient.changeWorkingDirectory("www.tempogara.it");
				    ftpclient.changeWorkingDirectory("appUpload");
				    if(!ftpclient.changeWorkingDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()))){
				    	ftpclient.makeDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()));
				    	ftpclient.changeWorkingDirectory(new SimpleDateFormat("ddMMyyyy").format(new Date()));
				    }
				}
			} catch (SocketException e1) {
				log.add("Problemi di connessione al server \n");
				count++;
				publishProgress(count);
				log.clear();
				e1.printStackTrace();
			} catch (IOException e1) {
				log.add("Problemi di connessione al server \n");
				count++;
				publishProgress(count);
				log.clear();
				e1.printStackTrace();
			}
			if(!multiple){
					fTemp= new File(DirPath+"/"+appData.tagsFile[0]);
						
					if (String.valueOf(ftpclient.getReplyCode()).startsWith("2")) {
						log.add("Connessione effettuata con successo \n Invio in corso \n");
						count++;
						publishProgress(count);
						log.clear();
						try {
						ftpclient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
				        ftpclient.enterLocalPassiveMode();
				        FileInputStream in = new FileInputStream(fTemp);
				        boolean result = ftpclient.storeFile(fTemp.getName(), in);
				        if(result){
				        	log.add("Upload su FTP effettuato con successo - "+new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(new Date())+" \n");
							count++;
							publishProgress(count);
							log.clear();
							corretto=true;
				        }else{
				        	log.add("Upload non effettuato \n");
				        	log.add(ftpclient.getReplyString()+" \n");
							count++;
							publishProgress(count);
							log.clear();
				        }
							in.close();

						} catch (IOException e) {
							e.printStackTrace();
						}

				}else{
					log.add("Upload non effettuato \n");
		        	log.add(ftpclient.getReplyString()+" \n");
					count++;
					publishProgress(count);
					log.clear();
				}
			}else{
				
				for(int i = 0; i<appData.tagsFile.length;i++){
					fTemp= new File(DirPath+"/"+appData.tagsFile[i]);//files.get(i));
					if (String.valueOf(ftpclient.getReplyCode()).startsWith("2")) {
						log.add("Connessione effettuata con successo \n Invio in corso \n");
						count++;
						publishProgress(count);
						log.clear();
						try {
						ftpclient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
				        ftpclient.enterLocalPassiveMode();
				        FileInputStream in = new FileInputStream(fTemp);
				        boolean result = ftpclient.storeFile(fTemp.getName(), in);
				        if(result){
				        	log.add("Upload su FTP effettuato con successo - "+new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(new Date())+" \n");
							count++;
							publishProgress(count);
							log.clear();
							corretto=true;
				        }else{
				        	log.add("Upload non effettuato \n");
				        	log.add(ftpclient.getReplyString()+" \n");
							count++;
							publishProgress(count);
							log.clear();
				        }
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
		
				}else{
					log.add("Upload non effettuato \n");
			    	log.add(ftpclient.getReplyString()+" \n");
					count++;
					publishProgress(count);
					log.clear();
				}
			}
		}
			if(corretto){
			    tg.startTone(ToneGenerator.TONE_PROP_BEEP);
				if(multiple){
					log.clear();
					log.add("Invio dei file corretto");
					count++;
					publishProgress(count);
				}
			}else if(multiple){
				log.clear();
				log.add("Invio dei file non corretto");
				log.add(ftpclient.getReplyString());
				count++;
				publishProgress(count);
			}
			ftpclient.logout();
	        ftpclient.disconnect();

		}
}